using UnityEngine;
using System.Collections;

public class FadeDemo : MonoBehaviour {

    private static bool ready;

    private static  float currentValue = 0;
    private static float fadeAmount;

    private static float amount = 1f;

    static ArrayList fadeIn = new ArrayList();
    static ArrayList fadeOut = new ArrayList();


    void Update()
    {
        if(ready)
        {

            In();
            Out();

            currentValue += amount * Time.deltaTime;

            if (currentValue >= 1)
            {
                ready = false;
                currentValue = 0;

                Fade(fadeIn, 1);
                Fade(fadeOut, 0);

            }
        }
    }

    private void In()
    {
        Fade(fadeIn, currentValue);

    }

    private void Out()
    {
        Fade(fadeOut, 1-currentValue);
    }

    public void FadeIn(Transform target)
    {
        currentValue = 0;
        fadeIn.Clear();
        fadeOut.Clear();
        fadeIn.Add(target);
        foreach (Transform obj in target.transform)
        {
            Setup(fadeIn, obj);
        }

        ready = true;
    }


    public void FadeOut(Transform target)
    {
        fadeIn.Clear();

        fadeOut.Clear();

        fadeOut.Add(target);

        foreach (Transform obj in target.transform)
        {
            Setup(fadeOut, obj);
        }
            
        Fade(fadeOut, 0);
    }

    public void FadeRoom(Transform to,Transform from)
    {
        fadeIn = new ArrayList();
        fadeOut = new ArrayList();

        fadeIn.Add(to);
        fadeOut.Add(from);

        foreach (Transform obj in to.transform)
        {
            Setup(fadeIn,obj);
        }
        foreach (Transform obj in from.transform)
        {
            Setup(fadeOut, obj);
        }

        ready = true;
    }

    private void Setup(ArrayList targetArray, Transform target)
    {
        targetArray.Add(target);

        foreach (Transform obj in target.transform)
        {
            Setup(targetArray,obj);
            targetArray.Add(obj);
        }
    }

    void Fade(ArrayList list, float i)
    {
        foreach (Transform obj in list)
        {
            if (obj)
            {
                if (obj.renderer)
                {
                    if (!obj.GetComponent<TextMesh>())
                    {
                        if (obj.renderer.material.shader != Shader.Find("Transparent/Diffuse"))
                            obj.renderer.material.shader = Shader.Find("Transparent/Diffuse");
                    }

                    obj.renderer.material.color = new Color(obj.renderer.material.color.r, obj.renderer.material.color.g, obj.renderer.material.color.b, i);
                }
            }
        }
    }

}